package cn.design;

import cn.design.realize.AddNonTerminalExpression;
import cn.design.realize.Context;
import cn.design.realize.DivisionNonTerminalExpression;
import cn.design.realize.Expression;
import cn.design.realize.MultiNonTerminalExpression;
import cn.design.realize.SubNonTerminalExpression;
import cn.design.realize.VariableTerminalExpression;

/**
 * @author dlq
 * @description  解释器的客户端角色
 * @date 2020/9/29 10:00
 * @since 1.0
 */
public class InterpreterClientDemo {
    public static void main(String[] args) throws Exception {
        //实现一个 加减乘除的 一个 解释器
        //1.定义一个环境，然后在环境中存值
        Context context = new Context();
        context.putVariable("X",3);
        context.putVariable("Y",6);
        context.putVariable("Z",9);

        //2.定义变量
        //终结符表达式
        VariableTerminalExpression XVariable = new VariableTerminalExpression("X");
        VariableTerminalExpression YVariable = new VariableTerminalExpression("Y");
        VariableTerminalExpression ZVariable = new VariableTerminalExpression("Z");
        VariableTerminalExpression MVariable = new VariableTerminalExpression("M");

        //3.定义符号
        //终结符表达式
        try {
            //测试不存在的变量
            Expression addExpression = new AddNonTerminalExpression(ZVariable,MVariable);
            addExpression.interpret(context);
        }catch (Exception e){
            System.err.println(e.getMessage());
        }
        // ((Z+Y)*X-Y)/Y ==((9+6)*3 - 9)/6
        Expression addExpression = new AddNonTerminalExpression(ZVariable,YVariable);
        //addExpression.interpret(context); 也是一个结果

        Expression multiExpression= new MultiNonTerminalExpression(addExpression,XVariable);
        Expression subExpression= new SubNonTerminalExpression(multiExpression,YVariable);
        Expression divExpression= new DivisionNonTerminalExpression(subExpression,YVariable);
        System.out.printf("((Z+Y)*X-Y)/Y = %s\n",divExpression.interpret(context));

    }

}
